<?php
defined('IN_XLP') or exit('Access Denied');

class sellerAction extends commonAction {

    function __construct() {
        parent::__construct();
        parent::_checkLogin();
        G('path_mod', 2);
    }


    /*
     * 商户列表
     */
    public function index() {

        $page  = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $limit = ($page - 1)*20;

        $seller_list = M('seller')
            ->field('*')
            ->limit("$limit,20")
            ->findAll();

        $total = M('seller')->getTotal();

        //昵称
        $uid_arr = array();
        foreach ($seller_list as $v) {
            $uid_arr[] = $v['uid'];
        }
        $uids = implode(',', $uid_arr);
        if(empty($uids)) $uids = 0;

        $sql = "SELECT u.`uid`, u.`nickname`, v.`title`
                FROM __PRE__user u,__PRE__village v
                WHERE u.`uid` in ($uids)
                AND v.`vid`=u.`village_id`";

        $result = M()->query($sql);
        // z($result);


        $temp = array();
        foreach ($result as $v) {
            $temp[$v['uid']] = array(
                'nickname' => empty($v['nickname']) ? '' : $v['nickname'],
                'village'  => empty($v['title']) ? '' : $v['title'],
            );
        }

        
        foreach ($seller_list as $k => $v) {
            $seller_list[$k]['nickname']  = isset($temp[$v['uid']]['nickname']) ? $temp[$v['uid']]['nickname'] : '';
            $seller_list[$k]['village']   = isset($temp[$v['uid']]['village']) ? $temp[$v['uid']]['village'] : '';
            $seller_list[$k]['reg_time']  = date('Y-m-d H:i:s', $v['reg_time']);
            $seller_list[$k]['status']    = $v['passed'] ? '已通过' : '<span class="red">尚未通过</span>';
        }
        
        
        // z($seller_list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('seller_list', $seller_list);
        $this->display();
    }


    /*
     * 添加商户
     */
    public function add() {

        if(count($_POST)) {
            //是否关注及加入社区
            $uid = $this->_postid('uid');
            $this->_isIn($uid);
            //是否重复添加
            $result = M('seller')
                ->where(array('uid'=>$uid))
                ->find();
            if($result) {
                $this->JsonReturn('已经申请过商户资格了', null, 0);
            }

            //商户5位特征码
            $seller_code = D('seller')->genSellerCode($uid);

            $data = $this->_input();
            $data['reg_time']    = TIME;
            $data['seller_code'] = $seller_code;

            $result = M('seller')->insert($data);
            if($result) {
                $this->JsonReturn('添加商户成功', null, 1);
            } else {
                $this->JsonReturn('添加商户失败', null, 0);
            }
        }

        $this->display();
    }

    /*
     * 编辑商户
     */
    public function edit() {

        if(count($_POST)) {
            $uid  = $this->_postid('uid');
            $data = $this->_input();
            M('seller')->update($data, array('uid'=>$uid));
            $this->JsonReturn('编辑商户成功', null, 1);
        }

        $uid = $this->_getid('uid');
        $seller_info = M('seller')
            ->where(array('uid'=>$uid))
            ->find();

        $this->assign('seller_info', $seller_info);
        $this->display();
    }

    /*
     * 审核通过
     */
    public function pass() {
        $uid = $this->_postid('uid');
        M('seller')->update(array('passed'=>1), array('uid'=>$uid));
        //查询商户码
        $result = M('seller')
            ->field('`seller_code`')
            ->where(array('uid'=>$uid))
            ->find();
        $seller_code = $result['seller_code'];

        $msg = "恭喜您通过审核成为结邻公社商户推广成员，您的商户推广码是：{$seller_code}，赶紧行动吧。";
        D('seller')->sendToUser($uid, $msg);
        $this->JsonReturn('ok', null ,1);
    }

    /*
     * 受邀用户列表
     */
    public function invite_list() {
        $page  = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $limit = ($page - 1)*20;

        $starttime  = empty($_GET['starttime']) ? null : strtotime($_GET['starttime']);
        $endtime    = empty($_GET['endtime']) ? null : strtotime($_GET['endtime']);
        $keyword    = empty($_GET['keyword']) ? null : trim($_GET['keyword']);

        //导出csv
        if(isset($_GET['export'])) {
            $limit = "";
        } else {
            $limit = " LIMIT $limit,20";
        }

        if(isset($keyword)) {
            $where = " AND s.`seller_shop` LIKE '%{$keyword}%'";
        } else {
            $where = "";
        }

        if(isset($starttime)) {
            $where .= " AND i.`reg_time` >= $starttime";
        }
        if(isset($endtime)) {
            $where .= " AND i.`reg_time` <= $endtime";
        }

        $sql = "SELECT i.`uid`, i.`seller_uid`, i.`sale_code`, i.`reg_time`,
                s.`seller_name`, s.`seller_shop`,
                u.`nickname`
                FROM __PRE__seller s, __PRE__seller_invite i, __PRE__user u
                WHERE u.`uid`=i.`uid` AND s.`uid`=i.`seller_uid`
                $where
                ORDER BY i.`reg_time` DESC ";

        if(!isset($_GET['export'])) {
            $sql .= $limit;
        }
        //受邀用户列表
        $invite_list = M()->query($sql);
        // z($invite_list);
        if(isset($_GET['export'])) {
            $this->_export_invite($invite_list);
        }

        $sql = "SELECT COUNT(i.`uid`) total
                FROM __PRE__seller s, __PRE__seller_invite i
                WHERE s.`uid`=i.`seller_uid`
                $where ";
        $total = M()->query($sql);
        $total = $total[0]['total'];

        $this->assign('starttime', $starttime ? date('Y-m-d H:i:s', $starttime) : '');
        $this->assign('endtime', $endtime ? date('Y-m-d H:i:s', $endtime) : '');
        $this->assign('keyword', $keyword);

        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('invite_list', $invite_list);
        $this->display();
    }

    private function _export_invite($data) {
        $data_title = array('受邀用户','商户名称','注册时间');
        $data_list  = array();

        foreach ($data as $k => $v) {
            $data_list[] = array(
                'nickname'    => $v['nickname'],
                'seller_shop' => $v['seller_shop'],
                'reg_time'    => "\t".date('Y-m-d H:i:s', $v['reg_time']),
            );
        }

        load('csv');
        $csv = new csv();
        $csv->write($data_title, $data_list, '商家邀请用户表'.date('Y-m-d'));
        exit;
    }

    /*
     * 处理表单输入
     */
    private function _input() {
        $tablefields = M('seller')->getTableFields();
        $data = array();
        foreach ($tablefields['fields'] as $key => $value) {
            if(!isset($_POST[$key])) continue;
            if(is_string($this->_post($key))) {
                $data[$key] = trim($this->_post($key));
            }
        }

        return $data;
    }

    /*
     * 是否关注我们和入驻小区
     */
    private function _isIn($uid) {
        $result = M('user')
            ->field('`village_id`')
            ->where(array('uid'=>$uid))
            ->find();

        if(!$result) {
            $this->JsonReturn('UID不存在', null, 0);
        }
        if(!$result['village_id']) {
            $this->JsonReturn('该商户没有入驻小区', null, 0);
        }

        return true;
    }
}